import React, {PureComponent, Fragment} from "react";
import moment from "moment";
import {Row, Col, Form,  Card, Input, Icon, Button, Divider, message, Radio, InputNumber } from "antd";
import DescriptionList from '../../../components/DescriptionList';
import Upload from "../../../components/Upload";
import MaintainPerson from '../../Form/MaintainPerson';
import SparesTable from "./SparesTable";
import Authorized from '../../../utils/Authorized';
import styles from '../../Pbulic.less';

const FormItem = Form.Item;
const { TextArea } = Input;
const { Description } = DescriptionList;
const RadioGroup = Radio.Group;

const beforeUpload = file => {
  const isJPG = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJPG) {
    message.error("仅允许上传JPG、PNG文件!");
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error("图片文件不能大于2MB!");
  }
  return isJPG && isLt2M;
};

@Form.create()
export default class Acceptance extends PureComponent {
  constructor(props) {
    super(props);
    this.state={
      fileList: [],
      selectHandleResult:"1",
    }
  }


  componentDidMount() {

  }



  handleFormSubmit(type,e) {
    e.preventDefault();
    const {dispatch, repairId, form} = this.props;
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const addType = type==1 ? 'examine' : type==2 ? 'acceptance' : null;
        if(values.maintenanceInfo){
          values.maintenanceId=values.maintenanceInfo.maintenanceId;
          values.repairPerson=values.maintenanceInfo.userId;
          values.maintenanceInfo=undefined;
        }


        if(addType){
          dispatch({
            type: `repair/fetch_repair_${addType}`,
            payload: {
              ...values,
              repairId,
            }
          }).then(() => {
            this.handleReset();
            message.success(`维修${type==1 ? '审核' : type==2 ? '验收' : ''}已处理`);
          }).then(() => {
            dispatch({
              type: "repair/fetch_repair_info",
              payload: {
                repairId,
              }
            }).then(()=>{
              dispatch({
                type: "repair/fetch_repair_handle",
                payload: {
                  repairId,
                }
              })
            })

          });
        }

      }
    });
  }

  handleSubmitStatus(type,e) {
    e.preventDefault();
    const {dispatch, repairId, form} = this.props;
    dispatch({
      type: `repair/fetch_repair_status_${type}`,
      payload: {
        repairId,
      }
    }).then(() => {
      message.success(`${type==="examine" ? '审核' : type==='acceptance' ? '验收' : ''}正在处理中`);
    }).then(() => {
      dispatch({
        type: "repair/fetch_repair_info",
        payload: {
          repairId,
        }
      }).then(()=>{
        dispatch({
          type: "repair/fetch_repair_handle",
          payload: {
            repairId,
          }
        })
      })
    });
  }

  handleReset = () => {
    this.setState({
      fileList: [],
    })
    this.props.form.resetFields();
  };

  // 多图上传时间
  handleChangePicUpload = ({fileList}) => this.setState({fileList})

  uploadPic = e => {
    if (Array.isArray(e)) {
      return e;
    }
    const filelist =
      e &&
      e.fileList.reduce((arr, current) => {
        if (
          current.response &&
          current.response.data &&
          current.response.data.token
        ) {
          return arr.concat(current.response.data.token);
        } else {
          if (current.status && current.status === "error") {
            return arr.concat([]);
          } else {
            return arr.concat(current.uid);
          }
        }
      }, []);
    return filelist;
  };

  handleChangeResult = e =>{
    this.setState({
      selectHandleResult:e.target.value
    });
    this.props.form.setFieldsValue({
      processDesc:e.target.value==="1" ? '审核通过' : undefined
    })
  }

  // 维保单位关联人搜索事件-------------------------------------
  handleSearchMaintain = ( value ) =>{
    const { dispatch } = this.props;
    const maintenanceId=value.maintenanceId;
    const userId=value.userId;
    const loadData=value.loadData;

    this.setState({
      maintenanceId,
    })

    if(userId===0){
      // 清空子节点操作
      dispatch({
        type: 'global/fetch_clear_maintenman',
      })
    }

    if(loadData && maintenanceId!==0){
      // userId!=0 && this.handleChageMaintenance(maintenanceId);
      dispatch({
        type: 'global/fetch_select_maintenman',
        payload: {
          deptId:maintenanceId,
        },
      })
    }
  }
  checkMaintain =  (rule, value, callback) => {
    if (value && value.userId!==0) {
      callback();
      return;
    }
    callback('请选择维保单位及相关人员');
  }


  render() {

    const { selectSource,detaildata, data, status, repairStatus, lastStatus, baseUrl} = this.props;
    const { fileList, selectHandleResult} = this.state;
    const { getFieldDecorator } = this.props.form;


    const uploadButton = (
      <div>
        <Icon type="plus"/>
        <div className="ant-upload-text">上传</div>
      </div>
    );

    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 16 }
    };

    const formItemLayoutone = {
      labelCol: { span: 4 },
      wrapperCol: { span: 16 }
    };


    //01待办、02审核中、03已审核、04已受理、05验收中、06结束
    return (
      <Fragment>
        {/* 验收显示 -- 对应状态 05结束 */}
        {
          status == "07" &&
          <Fragment>
            <DescriptionList size="large" title={"结束"} col={2}  style={{marginBottom: 32}}>
              <Description term="处理时间">{data.createTime && moment(data.createTime).format("YYYY-MM-DD HH:mm")}</Description>
              {/*<Description term="完成时间">{data.completeTime && moment(data.completeTime).format("YYYY-MM-DD HH:mm")}</Description>*/}
              <Description term="验收结果">{data.operateCon}</Description>
              <Description term="验收人">{data.handlerName}</Description>
              <Description term="描述">{data.handleResult}</Description>
            </DescriptionList>
          </Fragment>
        }

        {/* 验收中（包括验收表单） */}
        {
          status === "06" && repairStatus==="06" && lastStatus==="06" &&
          <Fragment>
            {/* 验收表单 -- 对应状态 05验收中 */}
            <Authorized authority={'10147'} noMatch={
              // 验收中
              <DescriptionList size="large" title={"验收中"} col={2}  style={{marginBottom: 32}}>
              </DescriptionList>
            }>
              {/*<DescriptionList size="large" title={"验收"} style={{marginBottom: 32}}>*/}
                <Form layout="horizontal">
                  <Row gutter={24} className={styles.info_form}>
                    <Col span={24}>
                      <FormItem {...formItemLayoutone} label="接收时间">
                        {data.createTime && moment(data.createTime).format("YYYY-MM-DD HH:mm")}
                      </FormItem>
                    </Col>
                    <Col span={12}>
                      <FormItem {...formItemLayout} label="审核结果">
                        {getFieldDecorator('handleResult', {
                          rules: [
                            { required: true, message: "请选择审核结果" },
                          ]
                        })(
                          <RadioGroup>
                            <Radio value="1">通过</Radio>
                            <Radio value="0">不通过</Radio>
                          </RadioGroup>
                        )}
                      </FormItem>
                    </Col>
                    <Col span={12}>
                      <FormItem {...formItemLayout} label={"验收人"}>
                        {data.handler}
                      </FormItem>
                    </Col>
                    <Col span={24}>
                      <FormItem {...formItemLayoutone} label="描述" colon={false}>
                        {getFieldDecorator("processDesc", {
                          rules: [{max: 200, message: "不超过200个字"}]
                        })(
                          <TextArea
                            placeholder="请输入描述"
                            autosize={{minRows: 3, maxRows: 6}}
                          />
                        )}
                      </FormItem>

                    </Col>


                    <Col span={16} push={4} style={{marginTop:15}}>
                      <FormItem
                        {...formItemLayoutone}
                        // label="设备图片"
                        extra={<span>支持jpg、png<br/>图片大小不超过2M</span>}
                      >
                        {getFieldDecorator("repairPhotoArray", {
                          valuePropName: "file",
                          getValueFromEvent: this.uploadPic
                        })(
                          <Upload
                            listType="picture-card"
                            fileList={fileList}
                            // onPreview={this.handlePreview}
                            onChange={this.handleChangePicUpload}
                            beforeUpload={beforeUpload}
                          >
                            {fileList.length >= 5 ? null : uploadButton}
                          </Upload>
                        )}
                      </FormItem>
                    </Col>

                  </Row>
                  <Row gutter={24}>
                    <Col span={24} style={{textAlign: 'center', padding: 30}}>
                      <Button
                        onClick={this.handleFormSubmit.bind(this,2)}
                        type="primary"
                        size="large"
                        style={{marginRight: 15}}
                        // loading={loading.model_submit}
                      >
                        提交
                      </Button>
                      <Button
                        onClick={this.handleReset.bind(this)}
                        type="default"
                        size="large"
                      >
                        重置
                      </Button>
                    </Col>
                  </Row>
                </Form>
              {/*</DescriptionList>*/}
            </Authorized>
          </Fragment>
        }

        {/* 待验收（包括验收表单） */}
        {
          status === "05" && repairStatus==="05" && lastStatus==="05" &&
          <Fragment>
            <DescriptionList size="large" title={"待验收"} col={2}  style={{marginBottom: 32}}>
              {
                <Authorized authority={'10147'} >
                  <Row gutter={24}  style={{marginTop: 32,marginBottom: 32,textAlign:'center'}}>
                    <Col span={24}>
                      <Button
                        onClick={this.handleSubmitStatus.bind(this,'acceptance')}
                        type="primary"
                        size="large"
                        // loading={loading.model_submit}
                      >
                        验收
                      </Button>
                    </Col>
                  </Row>
                </Authorized>
              }
            </DescriptionList>
          </Fragment>
        }


        {/* 受理显示 -- 对应状态 04已受理 */}
        {
          status == "04" &&
          <Fragment>
            <DescriptionList size="large" title={"受理"} col={2}  style={{marginBottom: 32}}>
              <Description term="接收时间">{data.createTime && moment(data.createTime).format("YYYY-MM-DD HH:mm")}</Description>
              <Description term="完成时间">{data.completeTime && moment(data.completeTime).format("YYYY-MM-DD HH:mm")}</Description>
              <Description term="受理人">{data.creatorName}</Description>
              <Description term="描述">{data.operateCon}</Description>
            </DescriptionList>
            <DescriptionList size="large" >
              <Description>
                {
                  data.photoList && data.photoList.length > 0 &&
                  <div>
                    <Upload
                      listType="picture-card"
                      fileList={data.photoList.map(item=>{
                        item.url = baseUrl+item.url;
                        return item;
                      })}
                      disabled={true}
                      // onPreview={this.handlePreview}
                    />
                  </div>
                }
              </Description>
            </DescriptionList>
            {
              data.processId &&
              <DescriptionList size="large" col={1} style={{marginTop:24}}>
                <Description term="备品附件">&nbsp;</Description>
                <div style={{margin:'0 2px 50px 0'}}>
                  <SparesTable processId={data.processId} />
                </div>
              </DescriptionList>
            }

          </Fragment>
        }

        {/* 审核结果 -- 对应状态 03已审核 */}
        {
          status == "03" &&
          <Fragment>
            <DescriptionList size="large" title={"审核"} col={2}  style={{marginBottom: 32}}>
              <Description term="接收时间">{data.createTime && moment(data.createTime).format("YYYY-MM-DD HH:mm")}</Description>
              <Description term="完成时间">{data.completeTime && moment(data.completeTime).format("YYYY-MM-DD HH:mm")}</Description>
              {/*<Description term="审核结果">{data.handleResult=="1" ? '通过': data.handleResult=="2" ? '误报' : '不通过' }</Description>*/}
              <Description term="审核结果">{data.remark }</Description>
              <Description term="审核人">{data.creatorName}</Description>
              <Description term="描述">{data.operateCon}</Description>
            </DescriptionList>
          </Fragment>
        }


        {/* 审核中（包括审核表单） */}
        {
          status === "02" && repairStatus==="02" && lastStatus==="02" &&
          <Fragment>
            {/* 审核表单 -- 对应状态 02审核中 */}
            <Authorized authority={'10146'} noMatch={
              // 审核中
              <DescriptionList size="large" title={"审核中"} col={2}  style={{marginBottom: 32}}>
              </DescriptionList>
            }>
              <DescriptionList size="large" title={"审核"} style={{marginBottom: 32}}>
                <Form layout="horizontal">
                  <Row gutter={24} className={styles.info_form}>
                    <Col span={24}>
                      <FormItem {...formItemLayoutone} label="接收时间">
                        {data.createTime && moment(data.createTime).format("YYYY-MM-DD HH:mm")}
                      </FormItem>
                    </Col>
                    <Col span={12}>
                      <FormItem {...formItemLayout} label="审核结果">
                        {getFieldDecorator('handleResult', {
                          initialValue:"1",
                          rules: [
                            { required: true, message: "请选择审核结果" },
                          ]
                        })(
                          <RadioGroup onChange={this.handleChangeResult}>
                            <Radio value="1">通过</Radio>
                            <Radio value="0">不通过</Radio>
                            <Radio value="2">误报</Radio>
                          </RadioGroup>
                        )}
                      </FormItem>
                    </Col>
                    <Col span={12}>
                      <FormItem {...formItemLayout} label={"审核人"}>
                        {data.creatorName}
                      </FormItem>
                    </Col>
                    <Col span={12} className={styles.info_form_maintenance}>
                      <FormItem {...formItemLayout} label="维保单位" colon={false}>
                        {getFieldDecorator("maintenanceInfo", {
                          // initialValue: detailId === 0 ? (maintenanceId && maintenanceId!=0 ? {maintenanceId:maintenanceId,userId:0} : {maintenanceId:0,userId:0}) : {maintenanceId:detaildata.maintenanceId,userId:detaildata.repairPerson},
                          rules: [{required: true, message: "请选择维保单位及相关人员"},{validator: this.checkMaintain}],
                        })(
                          <MaintainPerson
                            // span={24}
                            placeholder={"请选择维修人"}
                            maintainData={selectSource.maintenance}
                            personnelData={selectSource.maintenman}
                            onChange={this.handleSearchMaintain}
                          />
                        )}
                      </FormItem>
                    </Col>
                    <Col span={12}>
                      <FormItem {...formItemLayout} label="处理时限" colon={false}>
                        {getFieldDecorator("handleTime", {
                          // initialValue: detailId === 0 ? undefined : detaildata.handleTime,
                          rules: [
                            { required: true, message: "请输入处理时限" },
                          ]
                        })(
                          <InputNumber placeholder="请输入" precision={0}  min={0} style={{width:100,marginRight:15}} />
                        )} 小时
                      </FormItem>
                    </Col>
                    <Col span={24}>
                      <FormItem {...formItemLayoutone} label="描述" colon={false}>
                        {getFieldDecorator("processDesc", {
                          initialValue: selectHandleResult==="1" ? "审核通过" : undefined,
                          rules: [
                            { required: selectHandleResult==="1" ? false : true, message: "请输入描述" },
                            {max: 200, message: "不超过200个字"}
                          ]
                        })(
                          <TextArea
                            placeholder="请输入描述"
                            autosize={{minRows: 3, maxRows: 6}}
                          />
                        )}
                      </FormItem>

                    </Col>
                  </Row>
                  <Row gutter={24}>
                    <Col span={24} style={{textAlign: 'center', padding: 30}}>
                      <Button
                        onClick={this.handleFormSubmit.bind(this,1)}
                        type="primary"
                        size="large"
                        style={{marginRight: 15}}
                        // loading={loading.model_submit}
                      >
                        提交
                      </Button>
                      <Button
                        onClick={this.handleReset.bind(this)}
                        type="default"
                        size="large"
                      >
                        重置
                      </Button>
                    </Col>
                  </Row>
                </Form>
              </DescriptionList>
            </Authorized>
          </Fragment>
        }




        {/* 待审核 */}
        {
          status === "01" && repairStatus==="01" && lastStatus==="01" &&
          <Fragment>
              {
                <Authorized authority={'10146'} >
                  <DescriptionList size="large" title={"待审核"} col={2}  style={{marginBottom: 32}}>
                  <Row gutter={24}  style={{marginTop: 32,marginBottom: 32,textAlign:'center'}}>
                    <Col span={24}>
                      <Button
                        onClick={this.handleSubmitStatus.bind(this,'examine')}
                        type="primary"
                        size="large"
                        // loading={loading.model_submit}
                      >
                        审核
                      </Button>
                    </Col>
                  </Row>
                  </DescriptionList>
                </Authorized>
              }
          </Fragment>
        }
        {/* 报修 -- 对应状态 01待办 */}
        {
          status === "01" &&
          <Fragment>
            <DescriptionList size="large" title={"报修"} col={2} style={{ marginBottom: 32 }}>
              <Description term="报修时间">{detaildata.createTime && moment(detaildata.createTime).format("YYYY-MM-DD HH:mm:ss")}</Description>
              <Description term="处理时限">{detaildata.handleTime} 小时</Description>
              <Description term="报修人">{detaildata.creatorName}</Description>
              <Description term="描述">{detaildata.handleResult}</Description>
            </DescriptionList>
            <DescriptionList col={1} size="large" >
              <Description>
                {
                  detaildata.repairPhotoArray && detaildata.repairPhotoArray.length > 0 &&
                  <div className={styles.upload_only_show}>
                    <Upload
                      listType="picture-card"
                      fileList={detaildata.repairPhotoArray.map(item=>{
                        item.url = baseUrl+item.url;
                        return item;
                      })}
                      disabled={true}
                      // onPreview={this.handlePreview}

                    />
                  </div>
                }
              </Description>
            </DescriptionList>
          </Fragment>
        }

      </Fragment>
    );
  }
}
